 <template>
  <div>
    <el-carousel trigger="click" :height="carouselHeight">
      <el-carousel-item v-for="url in imgArr" :key="url">
        <!-- <img :src="item" /> -->
        <!-- <el-image style="width: 100%; height: 580px" :src="url"></el-image> -->
        <el-image :src="url" class="carousel-image" @load="adjustCarouselHeight" />
      </el-carousel-item>

    </el-carousel>
    <div v-if="!token" v-loading="loading" element-loading-text="警录中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(0,0,0, 0.6)"
      :style="{ height: activeName === '登录' ? '280px' : '340px' }" class="login-container">
      <el-tabs type="card" v-model="activeName">
        <el-tab-pane label="登录" name="登录">
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
            <el-form-item prop="username">
              <el-input ref="username" v-model="loginForm.username" prefix-icon="el-icon-user" placeholder="请输入登录手机号" name="username" type="text" />
            </el-form-item>
            <el-form-item prop="password" required>
              <el-input :key="passwordType" prefix-icon="el-icon-lock" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="请输入登录密码" name="password"></el-input>
            </el-form-item>
            
            <div>
              <el-button type="primary" style="width: 100%" @click.native.prevent="handleLogin">
                登录</el-button>
            </div>
          </el-form>
          <el-button style="float:right; margin-right:16px" @click="forgotPassword" type="text">忘记密码</el-button>
        </el-tab-pane>
        <el-tab-pane label="注册" name="注册">
          <el-form autocomplete="off" size="mini" ref="register" :model="register" :rules="registerRules" class="login-form">
            <el-form-item prop="username">
              <el-input ref="username" v-model="register.username" prefix-icon="el-icon-user" placeholder="请输入手机号" name="username" type="text" />
            </el-form-item>
            <el-form-item prop="smsCaptchaResult">
              <el-input style="width: 180px; margin-right: 10px" :key="passwordType" prefix-icon="el-icon-chat-dot-square" v-model="register.smsCaptchaResult" placeholder="短信验证码"></el-input>
              <el-button type="primary" v-if="!countDown" :disabled="captchaDisable" @click="sendVerifyCode">发送</el-button>
              <el-button :disabled="true" type="primary" v-else>{{ countDown }}s</el-button>
            </el-form-item>
            <el-form-item prop="password">
              <el-input :key="passwordType" prefix-icon="el-icon-lock" v-model="register.password" auto-complete="new-password" name="password" :type="passwordType"
                placeholder="请输入密码(5-20位)"></el-input>
            </el-form-item>
            <el-form-item prop="conpassword">
              <el-input @input="inputChange" :key="passwordType" prefix-icon="el-icon-lock" v-model="register.conpassword" :type="passwordType" placeholder="请输入确认密码(5-20位)"></el-input>
            </el-form-item>
            <el-form-item>
              <vue-drag-verify ref="slideRef" text="向右滑动" successText="成功" :height="28" :width="260" :circle="false" @passcallback="onSuccess"></vue-drag-verify>
            </el-form-item>
            <div>
              <el-button type="primary" :disabled="!isSuccess" style="width: 100%" @click.native.prevent="registerClick">
                注册</el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-alert v-if="!!token && checkStatus" style="width: 90%; margin: auto" title="系统监测您还未提交资料，请前往 我的汇保 -> 管理中心 -> 账户维护 提交资料" type="warning">
    </el-alert>
    <el-alert v-if="walletPassSatus && checkStatusName !== '未审核'" style="width: 90%; margin: auto" title="系统监测您还未设置支付密码，请前往 我的汇保 -> 管理中心 -> 支付密码 设置支付密码" type="warning">
    </el-alert>
    <el-tabs v-if="token" v-model="activeInsure" type="card" class="vvv" style="margin: auto; width: 90%; margin-top: 20px">
      <el-tab-pane v-for="insure in insureList" :key="insure.insureTypeId" :label="insure.insureTypeName" name="first">
        <el-row :gutter="10">
          <el-col :span="12" v-for="(item, index) in insure.frontInsureInfos" :key="item.insureInfoId">
            <el-card :body-style="{ padding: '0px' }">
              <el-row :gutter="20">
                <el-col :span="12"><img :src="index === 0 ? waterway : highway" class="image" /></el-col>
                <el-col :span="12">
                  <div style="padding: 14px">
                    <!-- <span>{{ item.insureName }}</span> -->
                    <div class="bottom clearfix">
                      <div>
                        <span style="font-weight: bold; font-size: 20px">{{ item.insureName}}</span><span style="font-size: 14px; margin-left: 5px">{{"费率:" + item.rate + "起"}}</span>
                      </div>
                      <el-button class="insureBtn" type="primary" style="margin: 40px 0;" @click="insureClick(item.insureInfoId, item.insureName)">立即投保</el-button>
                    </div>
                  </div>
                </el-col>
              </el-row>

            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="修改密码" :visible.sync="dialogVisible" width="600px">
      <password-change :userName="loginForm.username" :spanData="24" @hidePasswordChange="hidePasswordChange"></password-change>
    </el-dialog>
  </div>
</template>
<script>
import banner1 from "@/assets/banner1.jpg";
import banner2 from "@/assets/banner2.jpg";
import banner3 from "@/assets/banner3.jpg";
import banner4 from "@/assets/banner4.jpg";
import highway from "@/assets/highway.jpg";
import waterway from "@/assets/waterway.webp";
import passwordChange from "../PasswordChange";
export default {
  components: {
    passwordChange,
  },
  computed: {
    checkStatusName() {
      const userInfo = localStorage.getItem("userInfo");
      if (userInfo) {
        const checkStatus = JSON.parse(userInfo).checkStatus;
        return checkStatus === "0"
          ? "未审核"
          : checkStatus === "1"
          ? "待审核"
          : checkStatus === "2"
          ? "审核未通过"
          : checkStatus === "3"
          ? "审核通过"
          : "";
      }
      return "";
    },
    checkPhone() {
      // 1.1 当输入的手机号大于10位进行验证
      if (this.register.username.length > 10) {
        return /^1[3-9]\d{9}$/.test(this.register.username);
      } else {
        return true;
      }
    },
    // 2.发送验证码按钮显示
    captchaDisable() {
      if (
        this.register.username.length > 10 &&
        this.checkPhone
      ) {
        return false;
      } else {
        return true;
      }
    },
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("用户名不能为空!"));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback("请输入正确的手机号码");
      }
      callback();
    };
    return {
      isSuccess: false,
      walletPassSatus: false,
      carouselHeight: "auto",
      userInfo: localStorage.getItem("userInfo"),
      checkStatus: false,
      dialogVisible: false,
      highway,
      waterway,
      skillTag: ["火灾", "爆炸", "雨淋", "盗抢"],
      insureList: [],
      uuid: "",
      smsUuid: "",
      activeName: "登录",
      activeInsure: "first",
      token: "",
      register: {
        username: "",
        smsCaptchaResult: "",
        password: "",
        conpassword: "",
      },
      registerRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        smsCaptchaResult: [
          { required: true, message: "短信验证码不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空" },
          {
            validator: (rule, value, callback) =>
              this.validateassword(rule, value, callback),
          },
          {
            validator: (rule, value, callback) =>
              this.consistent(rule, value, callback),
          },
        ],
        conpassword: [
          { required: true, message: "确认密码不能为空" },
          {
            required: true,
            validator: (rule, value, callback) =>
              this.validateassword(rule, value, callback),
          },
          {
            validator: (rule, value, callback) =>
              this.consistent(rule, value, callback),
          },
        ],
      },
      countDown: 0, // 倒计时
      loginForm: {
        username: "",
        password: "",
      },
      //登录规则
      loginRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          {
            message: "用户名不能为空",
            trigger: "blur",
            validator: validateUsername,
          },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) =>
              this.validateassword(rule, value, callback),
          },
        ],
      },
      loading: false,
      passwordType: "password",
      currentDate: new Date(),
      imgArr: [banner1, banner2, banner3, banner4],
    };
  },
  methods: {
    onSuccess() {
      this.isSuccess = true
    },
    getWallerData() {
      this.$post("/customer/wallet/info").then((res) => {
        if (res && res.code * 1 === 200) {
          this.walletPassSatus = !res.data.walletPassSatus
        }
      });
    },
    adjustCarouselHeight(event) {
      // 获取加载完成的图片元素
      const img = event.target;
      // 根据图片的高度来动态设置走马灯的高度
      this.carouselHeight = `${img.height}px`;
    },
    getCheckStatus() {
      const userInfo = localStorage.getItem("userInfo");
      if (userInfo) {
        const userInfoObj = JSON.parse(userInfo);
        this.checkStatus = userInfoObj.checkStatus * 1 !== 3;
        console.log(this.checkStatus, "this.checkStatus");
      } else {
        this.checkStatus = false;
      }
    },
    hidePasswordChange() {
      this.dialogVisible = false;
    },
    forgotPassword() {
      if (!this.loginForm.username) {
        this.$message.success("请输入手机号码");
        return;
      }
      // localStorage.setItem("username", this.loginForm.username)
      this.dialogVisible = true;
    },
    insureClick(insureInfoId, insureName) {
      this.getCheckStatus();
      if (this.checkStatus) {
        this.$message.warning(
          "您还未提交资料审核或审核还未通过，请耐心等待，或提交资料审核"
        );
        return;
      }
      this.$router.push({
        path: "/temp1",
        query: {
          insureInfoId,
          templateName: insureName,
        },
      });
    },
    inputChange() {
      this.$refs.register.validateField("password");
    },
    checkUsername() {
      // 1.1 当输入的手机号大于10位进行验证
      if (this.loginForm.username.length > 10) {
        return /^1[3-9]\d{9}$/.test(this.loginForm.username);
      } else {
        return true;
      }
    },
    consistent(rule, value, callback) {
      if (this.register.password != this.register.conpassword) {
        callback("两次输入的密码不一致");
      }
      callback();
    },
    validateassword(rule, value, callback) {
      if (value && (value.length < 5 || value.length > 21)) {
        callback("密码5-20位");
      }
      callback();
    },
    // 1.手机号码验证
    phoneNumberRight() {
      // 1.1 当输入的手机号大于10位进行验证
      if (this.username.length > 10) {
        return /^1[3-9]\d{9}$/.test(this.username);
      } else {
        return true;
      }
    },

    // 4.获取手机验证码
    async sendVerifyCode() {
      const params = {
        phone: this.register.username,
        uuid: this.uuid,
      };
      // 4.2 获取短信验证码
      this.$post("/customer/registerOfSms", params)
        .then((res) => {
          if (res && res.code * 1 === 200) {
            this.smsUuid = res.data;
            this.$message.success("短信发送成功");
            this.countDown = 60;
            this.timeIntervalID = setInterval(() => {
              this.countDown--;
              // 4.1 如果减到0 则清除定时器
              if (this.countDown == 0) {
                clearInterval(this.timeIntervalID);
              }
            }, 1000);
          } else {
            //
          }
        })
        .catch(() => {
          //
        });
    },
    validatePassword(rule, value, callback) {
      if (!value) {
        callback(new Error("密码不能为空!"));
      } else {
        callback();
      }
    },
    // 登录
    handleLogin() {
      const { password, username } = this.loginForm;
      const params = {
        password,
        username,
      };
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$post("/customer/login", params)
            .then((res) => {
              if (res) {
                if (res.code * 1 === 200) {
                  this.syncuserInfo(res.data);
                  this.token = localStorage.getItem("token");
                  this.getInfo();
                  this.$router.push({
                    path: "/homePage",
                    query: {
                      token: true,
                    },
                  });
                  this.$message.success("登录成功");
                }
              }
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    getInfo() {
      this.$get("/customer/getInfo").then((res) => {
        if (res && res.code) {
          localStorage.setItem("userInfo", JSON.stringify(res.data));
          this.getCheckStatus();
        }
      });
    },
    registerClick() {
      this.$refs.register.validate((valid) => {
        if (valid) {
          const params = {
            username: this.register.username,
            password: this.register.password,
            code: this.register.smsCaptchaResult,
            conpassword: this.register.conpassword,
            uuid: this.smsUuid,
          };
          this.$post("/customer/register", params).then((res) => {
            if (res && res.code * 1 === 200) {
              location.reload();
              this.$message.success("注册成功，需重新登录");
            }
          });
        }
      });
    },
    hideNumber(number) {
      return number.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    },
    syncuserInfo(token) {
      localStorage.setItem(
        "username",
        this.hideNumber(this.loginForm.username)
      );
      localStorage.setItem("token", token);
    },
    getInsureList() {
      this.$get("/index/getIndex").then((res) => {
        if (res && res.code * 1 === 200) {
          this.insureList = res.data;
        } else {
          this.insureList = [];
        }
      });
    },
    reload() {
      window.location.reload();
    },
  },
  mounted() {
    window.addEventListener("resize", this.reload);
    this.getInsureList();
    this.getCheckStatus();
    this.token = localStorage.getItem("token");

    if (this.token) {
      if (this.checkStatusName === '审核通过') {
        this.getWallerData()
      }
    }
  },
  destroyed() {
    window.removeEventListener("resize", this.reload);
  },
};
</script>
<style lang="less">
.indexPage {
  font-size: 16px;
  line-height: 40px;
  padding: 20px;
}
.indexPage:hover {
  background-color: #ffb340;
  color: #fff;
}
.login-container {
  z-index: 10;
  position: absolute;
  top: 170px;
  right: 40px;
  width: 300px;
  overflow: hidden;
  background-color: #fff;
  // background: ur1(-@/assets/bgo.jpg);
  background-size: 100% 100%;
  box-shadow: 0px 2px 14px 0px rgb(9 15 102 / 30%);
  border-radius: 4px;
  margin: auto;

  .carousel-image {
    width: 120%;
    /* 确保图片宽度充满父容器 */
    height: auto;
    /* 让图片高度自适应 */
    object-fit: cover; /* 填充整个容器，保持宽高比并裁剪多余部分 */
  }

  .login-form {
    position: relative;
    padding: 0px 20px 10px 20px;
    margin: 0 auto;
    overflow: hidden;

    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 2px;
    }
  }

  .tips {
    font-size: 12px;
    color: #000;
  }

  .title-container {
    position: relative;
    margin-top: 20px;

    .title {
      font-size: 18px;
      color: rgb(75, 75, 75);
      margin: 20px 0;
      text-align: center;
      font-weight: 500;
    }
  }

  .login-code {
    width: 33%;
    height: 28px;
    float: right;

    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }

  .login-code-img {
    height: 28px;
  }
}

.insureBtn:hover {
  background-color:#ffb340;
  color:#fff;
}

.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 150px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
  height: 240px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>
